<template>
  <div class="code-consistency p-4">
    <!-- 顶部横幅 -->
    <div class="overview-banner mb-6 bg-gradient-to-r from-purple-500 to-purple-700 text-white rounded-lg shadow-lg p-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold mb-2">代码标准一致性检查</h1>
          <p class="opacity-80">检查不同系统之间代码映射的一致性，及时发现并解决数据冲突问题</p>
        </div>
        <div class="flex space-x-4">
          <el-button type="primary" plain @click="handleRunCheck">
            <div class="i-carbon-play mr-1"></div>运行检查
          </el-button>
          <el-button type="primary" plain @click="handleExport">
            <div class="i-carbon-export mr-1"></div>导出报告
          </el-button>
        </div>
      </div>
    </div>

    <!-- 检查配置区域 -->
    <div class="config-container mb-6 bg-white p-4 rounded-lg shadow-md">
      <el-form :model="checkConfig" label-width="120px" label-position="right">
        <div class="grid grid-cols-3 gap-4">
          <el-form-item label="检查范围">
            <el-radio-group v-model="checkConfig.scope">
              <el-radio :label="'all'">全部代码</el-radio>
              <el-radio :label="'selected'">选定代码</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标准代码" v-if="checkConfig.scope === 'selected'">
            <el-select 
              v-model="checkConfig.standardCodes" 
              placeholder="请选择标准代码" 
              multiple 
              collapse-tags
              filterable
              class="w-full"
            >
              <el-option
                v-for="item in codeStandardOptions"
                :key="item.id"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检查类型">
            <el-checkbox-group v-model="checkConfig.checkTypes">
              <el-checkbox label="valueMapping">值映射一致性</el-checkbox>
              <el-checkbox label="codeStructure">代码结构一致性</el-checkbox>
              <el-checkbox label="nameMapping">名称映射一致性</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="检查系统">
            <el-select 
              v-model="checkConfig.systemIds" 
              placeholder="请选择系统" 
              multiple 
              collapse-tags
              filterable
              class="w-full"
            >
              <el-option
                v-for="item in systemOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 检查结果统计 -->
    <div class="stats-container mb-6 grid grid-cols-4 gap-6">
      <ArtStatsCard 
        title="检测项目" 
        :value="stats.totalChecks" 
        icon="i-carbon-document" 
        background="linear-gradient(135deg, #42b983, #2f9c6a)" 
        color="white"
      />
      <ArtStatsCard 
        title="已检查" 
        :value="stats.checkedItems" 
        icon="i-carbon-checkmark" 
        background="linear-gradient(135deg, #36a3f7, #0c80d1)" 
        color="white"
      />
      <ArtStatsCard 
        title="一致性问题" 
        :value="stats.issuesFound" 
        icon="i-carbon-warning-alt" 
        background="linear-gradient(135deg, #ffbe0b, #fb8c00)" 
        color="white"
      />
      <ArtStatsCard 
        title="严重问题" 
        :value="stats.severeIssues" 
        icon="i-carbon-warning-filled" 
        background="linear-gradient(135deg, #f56c6c, #e53935)" 
        color="white"
      />
    </div>

    <!-- 检查进度 -->
    <div v-if="checking" class="progress-container mb-6 bg-white p-4 rounded-lg shadow-md">
      <div class="flex items-center mb-2">
        <div class="text-lg font-bold mr-2">检查进度</div>
        <el-tag size="small">正在运行...</el-tag>
      </div>
      <el-progress 
        :percentage="checkProgress" 
        :format="format => `${checkProgress}%`" 
        :stroke-width="15"
      />
      <div class="text-sm text-gray-500 mt-2">正在检查: {{ currentCheckingItem }}</div>
    </div>

    <!-- 检查结果列表 -->
    <div class="result-container bg-white p-4 rounded-lg shadow-md">
      <div class="flex justify-between items-center mb-4">
        <div class="text-lg font-bold">一致性问题列表</div>
        <div class="filter-actions">
          <el-radio-group v-model="issueFilter" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="severe">严重</el-radio-button>
            <el-radio-button label="normal">一般</el-radio-button>
            <el-radio-button label="minor">轻微</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <ArtTable
        :data="filteredIssues"
        :loading="loading"
        :border="true"
        :stripe="true"
        :total="total"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :empty-text="emptyText"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="standardCode" label="标准代码" width="100" />
        <el-table-column prop="issueType" label="问题类型" width="120">
          <template #default="scope">
            <el-tag :type="getIssueTypeTagType(scope.row.issueType)">
              {{ getIssueTypeName(scope.row.issueType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.severity === 'severe' ? 'danger' : scope.row.severity === 'normal' ? 'warning' : 'info'"
              :effect="scope.row.severity === 'severe' ? 'dark' : 'light'"
            >
              {{ getSeverityName(scope.row.severity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="问题描述" min-width="250" show-overflow-tooltip />
        <el-table-column prop="systemA" label="系统A" width="100" />
        <el-table-column prop="systemB" label="系统B" width="100" />
        <el-table-column prop="detectedTime" label="检测时间" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'resolved' ? 'success' : 'danger'">
              {{ scope.row.status === 'resolved' ? '已解决' : '未解决' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleViewDetail(scope.row)">查看详情</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'resolved' ? 'info' : 'success'" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'resolved' ? '标记未解决' : '标记已解决' }}
            </el-button>
          </template>
        </el-table-column>
      </ArtTable>
    </div>

    <!-- 问题详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="问题详情"
      width="800px"
      append-to-body
      destroy-on-close
    >
      <template v-if="selectedIssue">
        <div class="grid grid-cols-2 gap-4 mb-4">
          <ArtDataListCard title="基本信息" :list="[
            { label: '问题ID', value: selectedIssue.id },
            { label: '标准代码', value: selectedIssue.standardCode },
            { label: '标准代码名称', value: selectedIssue.standardName },
            { label: '问题类型', value: getIssueTypeName(selectedIssue.issueType) },
            { label: '严重程度', value: getSeverityName(selectedIssue.severity) },
            { label: '状态', value: selectedIssue.status === 'resolved' ? '已解决' : '未解决' },
            { label: '检测时间', value: selectedIssue.detectedTime }
          ]" />
          
          <ArtDataListCard title="系统信息" :list="[
            { label: '系统A', value: selectedIssue.systemA },
            { label: '系统A代码', value: selectedIssue.systemACode },
            { label: '系统B', value: selectedIssue.systemB },
            { label: '系统B代码', value: selectedIssue.systemBCode }
          ]" />
        </div>

        <div class="mb-4">
          <div class="text-base font-medium mb-2">问题描述</div>
          <div class="bg-gray-50 p-3 rounded">{{ selectedIssue.description }}</div>
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div>
            <div class="text-base font-medium mb-2">系统A数据</div>
            <el-table :data="selectedIssue.systemAData" border stripe size="small">
              <el-table-column prop="code" label="代码" width="80" />
              <el-table-column prop="name" label="名称" min-width="120" />
              <el-table-column prop="value" label="值" width="80" />
            </el-table>
          </div>
          <div>
            <div class="text-base font-medium mb-2">系统B数据</div>
            <el-table :data="selectedIssue.systemBData" border stripe size="small">
              <el-table-column prop="code" label="代码" width="80" />
              <el-table-column prop="name" label="名称" min-width="120" />
              <el-table-column prop="value" label="值" width="80" />
            </el-table>
          </div>
        </div>

        <div class="mt-4">
          <div class="text-base font-medium mb-2">解决建议</div>
          <div class="bg-gray-50 p-3 rounded">{{ selectedIssue.suggestion }}</div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import ArtTable from '@/components/core/tables/ArtTable.vue'
import ArtStatsCard from '@/components/core/cards/ArtStatsCard.vue'
import ArtDataListCard from '@/components/core/cards/ArtDataListCard.vue'

// 检查配置
const checkConfig = reactive({
  scope: 'all',
  standardCodes: [],
  checkTypes: ['valueMapping', 'nameMapping'],
  systemIds: []
})

// 数据加载和分页
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 检查状态
const checking = ref(false)
const checkProgress = ref(0)
const currentCheckingItem = ref('')

// 统计数据
const stats = reactive({
  totalChecks: 247,
  checkedItems: 247,
  issuesFound: 18,
  severeIssues: 5
})

// 下拉选项
const codeStandardOptions = ref([
  { id: 1, code: 'GENDER', name: '性别代码', categoryName: '通用基础' },
  { id: 2, code: 'NATION', name: '民族代码', categoryName: '通用基础' },
  { id: 3, code: 'EDU_LEVEL', name: '教育程度', categoryName: '教育相关' },
  { id: 4, code: 'MARRIAGE', name: '婚姻状况', categoryName: '通用基础' },
  { id: 5, code: 'POLITICAL', name: '政治面貌', categoryName: '人事相关' }
])

const systemOptions = ref([
  { id: 1, name: '人事系统', code: 'HR' },
  { id: 2, name: '学籍系统', code: 'STU' },
  { id: 3, name: '财务系统', code: 'FIN' }
])

// 问题筛选
const issueFilter = ref('all')

// 问题数据
const issuesList = ref([
  {
    id: 1,
    standardCode: 'GENDER',
    standardName: '性别代码',
    issueType: 'valueMismatch',
    severity: 'severe',
    description: '人事系统和学籍系统的性别代码值映射存在冲突，人事系统用"M/F"表示男/女，学籍系统用"1/2"表示',
    systemA: '人事系统',
    systemACode: 'SEX',
    systemB: '学籍系统',
    systemBCode: 'XB',
    detectedTime: '2023-12-15 14:23:15',
    status: 'unresolved',
    systemAData: [
      { code: 'M', name: '男', value: 'M' },
      { code: 'F', name: '女', value: 'F' }
    ],
    systemBData: [
      { code: '1', name: '男', value: '1' },
      { code: '2', name: '女', value: '2' }
    ],
    suggestion: '建议在映射关系中明确规定两个系统之间的代码转换规则，确保数据交换时能正确转换。'
  },
  {
    id: 2,
    standardCode: 'NATION',
    standardName: '民族代码',
    issueType: 'incomplete',
    severity: 'normal',
    description: '人事系统的民族代码不完整，缺少部分少数民族的代码',
    systemA: '人事系统',
    systemACode: 'NATION',
    systemB: '标准代码库',
    systemBCode: 'NATION',
    detectedTime: '2023-12-15 14:25:47',
    status: 'unresolved',
    systemAData: [
      { code: '01', name: '汉族', value: '01' },
      { code: '02', name: '蒙古族', value: '02' }
    ],
    systemBData: [
      { code: '01', name: '汉族', value: '01' },
      { code: '02', name: '蒙古族', value: '02' },
      { code: '03', name: '回族', value: '03' },
      { code: '04', name: '藏族', value: '04' }
    ],
    suggestion: '建议更新人事系统的民族代码，补充缺失的民族代码。'
  },
  {
    id: 3,
    standardCode: 'POLITICAL',
    standardName: '政治面貌',
    issueType: 'nameMismatch',
    severity: 'minor',
    description: '人事系统和学籍系统对政治面貌的命名存在差异',
    systemA: '人事系统',
    systemACode: 'POLITICAL',
    systemB: '学籍系统',
    systemBCode: 'ZZMM',
    detectedTime: '2023-12-15 14:28:32',
    status: 'resolved',
    systemAData: [
      { code: '01', name: '中共党员', value: '01' },
      { code: '02', name: '共青团员', value: '02' }
    ],
    systemBData: [
      { code: '01', name: '党员', value: '01' },
      { code: '02', name: '团员', value: '02' }
    ],
    suggestion: '建议统一命名规范，确保各系统使用一致的名称。'
  },
  {
    id: 4,
    standardCode: 'EDU_LEVEL',
    standardName: '教育程度',
    issueType: 'structureMismatch',
    severity: 'severe',
    description: '财务系统的教育程度代码结构与标准库不一致，无法正确映射',
    systemA: '财务系统',
    systemACode: 'EDUCATION',
    systemB: '标准代码库',
    systemBCode: 'EDU_LEVEL',
    detectedTime: '2023-12-15 14:30:18',
    status: 'unresolved',
    systemAData: [
      { code: 'A', name: '本科及以下', value: 'A' },
      { code: 'B', name: '硕士', value: 'B' },
      { code: 'C', name: '博士', value: 'C' }
    ],
    systemBData: [
      { code: '10', name: '小学', value: '10' },
      { code: '20', name: '初中', value: '20' },
      { code: '30', name: '高中', value: '30' },
      { code: '40', name: '大专', value: '40' },
      { code: '50', name: '本科', value: '50' },
      { code: '60', name: '硕士', value: '60' },
      { code: '70', name: '博士', value: '70' }
    ],
    suggestion: '财务系统的教育程度代码粒度过粗，建议重新设计代码结构，或建立详细的映射关系。'
  },
  {
    id: 5,
    standardCode: 'MARRIAGE',
    standardName: '婚姻状况',
    issueType: 'valueMismatch',
    severity: 'severe',
    description: '学籍系统和人事系统的婚姻状况代码值存在冲突，可能导致数据不一致',
    systemA: '学籍系统',
    systemACode: 'HYZK',
    systemB: '人事系统',
    systemBCode: 'MARRIAGE',
    detectedTime: '2023-12-15 14:35:42',
    status: 'unresolved',
    systemAData: [
      { code: '1', name: '未婚', value: '1' },
      { code: '2', name: '已婚', value: '2' },
      { code: '3', name: '离婚', value: '3' },
      { code: '4', name: '丧偶', value: '4' }
    ],
    systemBData: [
      { code: '10', name: '未婚', value: '10' },
      { code: '20', name: '已婚', value: '20' },
      { code: '30', name: '离异', value: '30' },
      { code: '40', name: '丧偶', value: '40' }
    ],
    suggestion: '建议统一代码值，或在映射关系中明确规定转换规则。'
  }
])

// 问题详情
const detailDialogVisible = ref(false)
const selectedIssue = ref(null)

// 空数据提示
const emptyText = computed(() => {
  return checking.value ? '正在检查中...' : '暂无一致性问题'
})

// 根据筛选条件过滤问题
const filteredIssues = computed(() => {
  if (issueFilter.value === 'all') {
    return issuesList.value
  }
  return issuesList.value.filter(issue => issue.severity === issueFilter.value)
})

// 获取问题类型名称
const getIssueTypeName = (type: string) => {
  const typeMap = {
    'valueMismatch': '值映射冲突',
    'nameMismatch': '名称不一致',
    'structureMismatch': '结构不一致',
    'incomplete': '数据不完整'
  }
  return typeMap[type] || type
}

// 获取问题类型标签类型
const getIssueTypeTagType = (type: string) => {
  const typeMap = {
    'valueMismatch': 'danger',
    'nameMismatch': 'warning',
    'structureMismatch': 'danger',
    'incomplete': 'info'
  }
  return typeMap[type] || ''
}

// 获取严重程度名称
const getSeverityName = (severity: string) => {
  const severityMap = {
    'severe': '严重',
    'normal': '一般',
    'minor': '轻微'
  }
  return severityMap[severity] || severity
}

// 运行一致性检查
const handleRunCheck = () => {
  // 验证检查配置
  if (checkConfig.scope === 'selected' && checkConfig.standardCodes.length === 0) {
    ElMessage.warning('请选择要检查的标准代码')
    return
  }
  
  if (checkConfig.checkTypes.length === 0) {
    ElMessage.warning('请至少选择一种检查类型')
    return
  }
  
  if (checkConfig.systemIds.length < 2) {
    ElMessage.warning('请至少选择两个系统进行一致性检查')
    return
  }
  
  // 开始检查
  checking.value = true
  checkProgress.value = 0
  currentCheckingItem.value = '初始化检查环境...'
  
  // 模拟检查进度
  const interval = setInterval(() => {
    if (checkProgress.value < 100) {
      checkProgress.value += 5
      
      // 更新当前检查项目
      if (checkProgress.value < 20) {
        currentCheckingItem.value = '检查性别代码(GENDER)值映射一致性...'
      } else if (checkProgress.value < 40) {
        currentCheckingItem.value = '检查民族代码(NATION)值映射一致性...'
      } else if (checkProgress.value < 60) {
        currentCheckingItem.value = '检查政治面貌(POLITICAL)名称映射一致性...'
      } else if (checkProgress.value < 80) {
        currentCheckingItem.value = '检查教育程度(EDU_LEVEL)代码结构一致性...'
      } else {
        currentCheckingItem.value = '检查婚姻状况(MARRIAGE)值映射一致性...'
      }
    } else {
      clearInterval(interval)
      checking.value = false
      ElMessage.success('一致性检查完成')
      
      // 随机更新问题数量
      stats.issuesFound = Math.floor(Math.random() * 10) + 15
      stats.severeIssues = Math.floor(Math.random() * 5) + 3
      
      // 模拟新增一个问题
      const newIssue = {
        id: issuesList.value.length + 1,
        standardCode: checkConfig.standardCodes.length > 0 ? 
          checkConfig.standardCodes[0] : 'GENDER',
        standardName: '性别代码',
        issueType: 'valueMismatch',
        severity: 'severe',
        description: '发现新的映射冲突问题',
        systemA: '人事系统',
        systemACode: 'SEX',
        systemB: '财务系统',
        systemBCode: 'XB',
        detectedTime: new Date().toLocaleString(),
        status: 'unresolved',
        systemAData: [
          { code: 'M', name: '男', value: 'M' },
          { code: 'F', name: '女', value: 'F' }
        ],
        systemBData: [
          { code: '1', name: '男', value: '1' },
          { code: '2', name: '女', value: '2' }
        ],
        suggestion: '建议在映射关系中明确规定转换规则。'
      }
      
      issuesList.value.unshift(newIssue)
      total.value = issuesList.value.length
    }
  }, 200)
}

// 导出报告
const handleExport = () => {
  ElMessage.success('报告导出成功')
}

// 查看问题详情
const handleViewDetail = (row) => {
  selectedIssue.value = row
  detailDialogVisible.value = true
}

// 切换问题状态
const handleToggleStatus = (row) => {
  row.status = row.status === 'resolved' ? 'unresolved' : 'resolved'
  
  // 更新统计数据
  if (row.status === 'resolved') {
    if (row.severity === 'severe') {
      stats.severeIssues = Math.max(0, stats.severeIssues - 1)
    }
  } else {
    if (row.severity === 'severe') {
      stats.severeIssues++
    }
  }
  
  ElMessage.success(`问题已${row.status === 'resolved' ? '标记为已解决' : '标记为未解决'}`)
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  pageSize.value = size
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 初始化
onMounted(() => {
  // 默认选择两个系统
  checkConfig.systemIds = [1, 2]
  
  total.value = issuesList.value.length
})
</script>

<style scoped lang="scss">
.code-consistency {
  .overview-banner {
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: -50%;
      right: -50%;
      width: 100%;
      height: 200%;
      background-image: linear-gradient(
        45deg,
        rgba(255, 255, 255, 0.1) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.1) 50%,
        rgba(255, 255, 255, 0.1) 75%,
        transparent 75%,
        transparent
      );
      background-size: 20px 20px;
      transform: rotate(25deg);
      z-index: 1;
    }
  }
  
  /* 进度条样式 */
  :deep(.el-progress-bar__inner) {
    background-image: linear-gradient(to right, #42b983, #36a3f7, #ffbe0b, #f56c6c);
  }
}
</style> 